﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Client.TopLevel;

namespace PersApp
{
    public partial class TaskForm : Form
    {
        // members
        private IManagerEmployee mManager;
        private IEnumerable<TLTask> mTasks;
        private IEnumerable<TLEmployee> mEmployees;
        private TLTask selectedTask = null;
        private bool ShowOnlyUsersTasks = false;

        public TaskForm(IManagerEmployee manager, bool showOnlyUsersTasks)
        {
            mManager = manager;
            ShowOnlyUsersTasks = showOnlyUsersTasks;
            InitializeComponent();
            initTable();

            if (ShowOnlyUsersTasks)
            {
                buttonAdd.Enabled = false;
            }
        }

        private void initTable()
        {
            taskGridView.Columns.Add("Title", "Название");
            taskGridView.Columns.Add("StartTime", "Время начала");
            taskGridView.Columns.Add("EndTime", "Время завершения");
            taskGridView.Columns.Add("EstimationTime", "Расчетное время");
            taskGridView.Columns.Add("Cost", "Премия");
            taskGridView.Columns.Add("Penalty", "Штраф");
            taskGridView.Columns.Add("Employee", "Владелец");
            taskGridView.Columns.Add("State", "Статус");
           

            foreach (DataGridViewColumn column in taskGridView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            }

            refreshList();
        }

        private void refreshList()
        {
            taskGridView.Rows.Clear();

            mEmployees = mManager.GetAllEmployees();
            mTasks = mManager.GetAllTasks();
            TLEmployee currentEmployee = mManager.GetEmployee();

            if (mTasks == null) return;

            foreach (TLTask task in mTasks)
            {
                if (task == null) continue;
                TLEmployee employee = FindEmployeeById(task.EmployeeId);
                if (employee == null) continue;

                if (ShowOnlyUsersTasks && employee.Id != currentEmployee.Id)
                    continue;

                string owner = string.Empty;
                if (employee != null) owner = employee.Name;

                string endTime = string.Empty;
                if (task.EndTime.Year != 1)
                    endTime = task.EndTime.ToShortDateString();

                string state;
                if (endTime.Equals(String.Empty))
                {
                    state = "in process";
                }
                else
                {
                    state = "finished";
                }

                string estimTime = string.Empty;
                if (task.EstimationTime.Year != 1)
                    estimTime = task.EstimationTime.ToShortDateString();
                    

                int rowIndex = taskGridView.Rows.Add(
                    task.Title,
                    task.StartTime.ToShortDateString(),
                    endTime,
                    estimTime,
                    task.Cost,
                    task.Penalty,
                    owner,
                    state);

                taskGridView.Rows[rowIndex].Tag = task;
            }

            SetOwnerComboBoxItems();
        }

        private void SetOwnerComboBoxItems()
        {
            if (!ShowOnlyUsersTasks)
            {
                ownerComboBox.Items.Clear();
                foreach (TLEmployee empl in mEmployees)
                    ownerComboBox.Items.Add(empl.Name);
            }
            else
            {
                ownerComboBox.Text = mManager.GetEmployee().Name;
                ownerComboBox.Enabled = false;
                buttonAdd.Enabled = false;
            }
        }
        

        private TLEmployee FindEmployeeById(int id)
        {
            foreach (TLEmployee empl in mEmployees)
                if (empl.Id == id) return empl;
            return null;
        }

        private int GetEmployeeId(string name)
        {
            foreach (TLEmployee empl in mEmployees)
                if (empl.Name == name) return empl.Id;
            return -1;
        }

        private void taskGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                TLTask task = (TLTask)e.Row.Tag;
                bool result = mManager.DeleteTask(task);

                if (!result)
                    MessageBox.Show("Задача не удалена!");

                refreshList();
            }
            catch
            {
            }
        }

        private void taskGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try 
            {
                if (e.RowIndex < 0)
                    return;

                selectedTask = (TLTask)taskGridView.Rows[e.RowIndex].Tag;
                titleTextBox.Text = selectedTask.Title;
                if (selectedTask.EstimationTime.Year != 1)
                    estimationDateTimePicker.Value = selectedTask.EstimationTime;
                costTextBox.Text = selectedTask.Cost.ToString();
                penaltyTextBox.Text = selectedTask.Penalty.ToString();
            }
            catch
            {
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            try 
            {
                TLTask task = new TLTask();

                task.EmployeeId = GetEmployeeId(ownerComboBox.Text);
                if (task.EmployeeId == -1)
                {
                    MessageBox.Show("Пользователя с таким именем не существует.");
                    return;
                }

                if (titleTextBox.Text != string.Empty)
                    task.Title = titleTextBox.Text;
                else
                {
                    MessageBox.Show("Необходимо указать название задачи.");
                    return;
                }

                task.StartTime = DateTime.Now;
                task.EstimationTime = estimationDateTimePicker.Value;

                try
                {
                    task.Cost = Convert.ToInt32(costTextBox.Text);
                }
                catch
                {
                    task.Cost = 0;
                }

                try
                {
                    task.Penalty = Convert.ToInt32(penaltyTextBox.Text);
                }
                catch
                {
                    task.Penalty = 0;
                }

                if (mManager.AddTask(task))
                {
                    refreshList();
                }
                else
                {
                    MessageBox.Show("Не удалось добавить задачу.");
                }
            }
            catch
            {
            }
        }

        private void finishButton_Click(object sender, EventArgs e)
        {
            try
            {
                selectedTask.EndTime = DateTime.Now;
                if (!mManager.FinishTask(selectedTask))
                {
                    MessageBox.Show("Не удалось завершить задачу.");
                }
                else refreshList();
            }
            catch
            {
            }
        }
    }
}
